package top.fullj.remoting.provider;

import java.util.HashMap;
import java.util.Map;

/**
 * @author bruce.wu
 * @since 2022/2/14 14:11
 */
public class ServiceRegistry {

    private static final ServiceRegistry INSTANCE = new ServiceRegistry();

    public static ServiceRegistry getInstance() {
        return INSTANCE;
    }

    private final Map<String, ServiceDelegate> registry = new HashMap<>();

    public void register(Object target) {
        Provider provider = target.getClass().getAnnotation(Provider.class);
        String name = provider.name();
        if (registry.containsKey(name)) {
            throw new IllegalStateException("duplicated service name: " + name);
        }
        ServiceConfig config = getConfig(provider);
        ServiceDelegate delegate = new ServiceDelegate(target, config);
        registry.put(name, delegate);
    }

    public ServiceDelegate lookup(String name) {
        return registry.get(name);
    }

    private ServiceConfig getConfig(Provider provider) {
        return new ServiceConfig(provider.name(), provider.type());
    }

}
